package org.example.mrrope.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jcajce.provider.keystore.util.JKSKeyStoreSpi;
import org.example.mrrope.service.PurchaseRequisitionService;
import org.example.mrrope.utils.DingUtil;
import org.example.mrrope.utils.FormUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@Slf4j
public class PurchaseRequisitionServiceImpl implements PurchaseRequisitionService {
    @Autowired
    private DingUtil dingUtil;

    @Override
    @Async
    public void generatePurchaseRequisitionFromBom(String id,String userId) {
        try {
            //得BOM单
            log.info("开始调用宜搭查询接口");
            JSONObject jsonObject = new JSONObject(dingUtil.getYidaById(id));
            JSONArray msJsonArray = dingUtil.getInnerTables(id, "FORM-3A8D681A77094B6DAF95EBB52ABF301DGFLW", "tableField_lwg8vm75");
            log.info("调用查询接口返回棉纱子表数据" + msJsonArray);
            JSONArray pjJsonArray = dingUtil.getInnerTables(id, "FORM-3A8D681A77094B6DAF95EBB52ABF301DGFLW", "tableField_lvxe56yi");
            log.info("调用查询接口返回配件表数据" + pjJsonArray);
            JSONArray bcpJsonArray = dingUtil.getInnerTables(id, "FORM-3A8D681A77094B6DAF95EBB52ABF301DGFLW", "tableField_lwed3a1x");
            log.info("调用查询接口返回半成品表数据" + bcpJsonArray);
            JSONArray szJsonArray = dingUtil.getInnerTables(id, "FORM-3A8D681A77094B6DAF95EBB52ABF301DGFLW", "tableField_lujgt57k");
            log.info("调用查询接口返回制绳表数据" + szJsonArray);
            // body
            int res = 1;
            String msArrayString = "";
            String pjArrayString = "";
            String bcpArrayString = "";
            String szArrayString = "";
            JSONArray msNewJsonArray = new JSONArray();
            JSONArray pjNewJsonArray = new JSONArray();
            JSONArray bcpNewJsonArray = new JSONArray();
            JSONArray szNewJsonArray = new JSONArray();
            Map<String, String> keyTransformMap = new HashMap<>();
            if (!msJsonArray.isEmpty()) {
                String jsonString = msJsonArray.toString();
                keyTransformMap.put("textField_lx2luc3v", "textField_ltzkj7lh");//名称
                keyTransformMap.put("textField_lwg902p8", "textField_ltzkj7li");//料号
                keyTransformMap.put("textField_lwg902p9", "textField_lup11dxw");//颜色
                keyTransformMap.put("numberField_lxvivx3m", "numberField_lye43pr1");//采购数量
                keyTransformMap.put("imageField_lxy4xj35", "imageField_ltzkj7lj");//图片
                msArrayString = extracted(jsonString, keyTransformMap, "棉纱", "KG", "未采购");
                msNewJsonArray = processJsonArray(msArrayString);//去重
                keyTransformMap.clear();
            }
            if (!pjJsonArray.isEmpty()) {
                String jsonString = pjJsonArray.toString();
                keyTransformMap.put("textField_lujgt59d", "textField_ltzkj7lh");
                keyTransformMap.put("textField_lujgt59f", "textField_ltzkj7li");
                keyTransformMap.put("textField_lx3ck53r", "textField_lup11dxw");
                keyTransformMap.put("numberField_lxwv7czp", "numberField_lye43pr1");//采购数量
                keyTransformMap.put("imageField_lwg902pf", "imageField_ltzkj7lj");
                keyTransformMap.put("textField_m2b8j9ti", "textField_lw4ngcq1");
                pjArrayString = extracted(jsonString, keyTransformMap, "配件", "无", "未采购");
                pjNewJsonArray = processJsonArray(pjArrayString);//去重
                keyTransformMap.clear();
            }
            if (!bcpJsonArray.isEmpty()) {
                String jsonString = bcpJsonArray.toString();
                keyTransformMap.put("textField_lwbmqipz", "textField_ltzkj7lh");
                keyTransformMap.put("textField_lujgt592", "textField_ltzkj7li");
                keyTransformMap.put("textareaField_m2ohpz46", "textField_lup11dxw");
                keyTransformMap.put("numberField_lxwv7czo", "numberField_lye43pr1");//采购数量
                keyTransformMap.put("imageField_lwt5fomx", "imageField_ltzkj7lj");
                jsonString = filterAndProcessJsonArray(jsonString, "textField_m4taj2ne");
                bcpArrayString = extracted(jsonString, keyTransformMap, "半成品", "无", "未采购");
                bcpNewJsonArray = processJsonArray(bcpArrayString);//去重
                keyTransformMap.clear();
            }
            if (!szJsonArray.isEmpty()) {
                String jsonString = szJsonArray.toString();
                keyTransformMap.put("textField_lxd6qtml", "textField_ltzkj7lh");
                keyTransformMap.put("textField_lujgt57l", "textField_ltzkj7li");
                keyTransformMap.put("textField_lxipl733", "textField_lup11dxw");
                keyTransformMap.put("numberField_lxwv7czn", "numberField_lye43pr1");//采购数量
                keyTransformMap.put("imageField_lxy4xj34", "imageField_ltzkj7lj");
                jsonString = filterAndProcessJsonArray(jsonString, "textField_m4t9bn9d");
                szArrayString = extracted(jsonString, keyTransformMap, "绳子", "无", "未采购");
                szNewJsonArray = processJsonArray(szArrayString);//去重
                keyTransformMap.clear();
            }
            if (!msNewJsonArray.equals("") || !pjArrayString.equals("")|| !bcpArrayString.equals("")|| !szArrayString.equals("")) {
                // 将JSON字符串转换为JSON对象
                List<Object> msJsonArrayList = msNewJsonArray.toList();
                List<Object> pjJsonArrayList = pjNewJsonArray.toList();
                List<Object> bcpJsonArrayList = bcpNewJsonArray.toList();
                List<Object> szJsonArrayList = szNewJsonArray.toList();
                // 合并JSON对象
                //通过 Stream.of 将多个列表合并成一个流，再使用 flatMap 将每个列表中的元素展平
                //使用 filter(list -> list != null) 确保每个列表都不为 null，防止 NullPointerException。
                JSONArray mergedArray = new JSONArray(
                        Stream.of(msJsonArrayList, pjJsonArrayList, bcpJsonArrayList, szJsonArrayList)
                                .filter(Objects::nonNull)
                                .flatMap(List::stream)
                                .collect(Collectors.toList())
                );
//                JSONArray mergedArray = new JSONArray(
//                        Stream.concat(msJsonArrayList.stream(), pjJsonArrayList.stream(), bcpJsonArrayList.stream(), szJsonArrayList.stream())
//                                .collect(Collectors.toList())
//                );
                log.info("合并后的数据" + mergedArray);
                JSONObject instanceJson = getInstanceJson(jsonObject, id, mergedArray);
                log.info("调用创建接口");
                //更新或修改
                //查询有没有当前请购单
                JSONObject searchFieldJson = new JSONObject();
                searchFieldJson.put("textField_lv5b06nc", jsonObject.getString("textField_lwt4u8ls"));
                searchFieldJson.put("textField_ltzkj7ld", jsonObject.getString("textField_lujgt578"));
                log.info("查询请购单开始:{}", jsonObject.getString("textField_lwt4u8ls"));
                String yiDaSearchReturnData_XSDD = dingUtil.yiDaSearchReturnData("FORM-A79E0E23CFFD49F5B5A802BEDA6B6AF6CCYW", searchFieldJson);//获取销售订单数据
                String resString = null;
                if (yiDaSearchReturnData_XSDD.equals("[]") || yiDaSearchReturnData_XSDD.equals("") || yiDaSearchReturnData_XSDD.equals("null")){
                    log.info("新增");
                     dingUtil.startInstance(instanceJson, userId, "FORM-A79E0E23CFFD49F5B5A802BEDA6B6AF6CCYW");
                }else{
                    log.info("更新");
                    JSONArray yiDaSearchReturnData_XSDDJsonArray = new JSONArray(yiDaSearchReturnData_XSDD);
//                    JSONObject xsddJSONObject = yiDaSearchReturnData_XSDDJsonArray.getJSONObject(0).getJSONObject("formData");
                    String instanceId = yiDaSearchReturnData_XSDDJsonArray.getJSONObject(0).getString("formInstanceId");
                    resString = dingUtil.UpdateYiDa(instanceId, instanceJson);
                }
                log.info("调用创建接口返回" + resString);
            }
            log.info("采购请购单生成结果" + res);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    @Async
    public void generatePackingPurchaseRequisitionFromBom(String id,String userId) {
        try {
            int res = 1;
            //得BOM单
            log.info("开始调用宜搭查询接口");
            JSONObject jsonObject = new JSONObject(dingUtil.getYidaById(id));
            log.info("调用查询接口返回BOM数据" + jsonObject);
            JSONObject searchJson = new JSONObject();
//            searchJson.put("textField_ly89l9at", jsonObject.get("textField_lujgt576"));
            searchJson.put("textField_lv5b06nc", jsonObject.get("textField_lwt4u8ls"));
            log.info("开始调用宜搭查询接口");
            JSONArray searchJsonArray = new JSONArray(dingUtil.yiDaSearchReturnData("FORM-A79E0E23CFFD49F5B5A802BEDA6B6AF6CCYW", searchJson));
            log.info("调用查询接口返回请购单数据" + searchJsonArray);
            JSONObject searchJsonReturnObject = new JSONObject();
            String bzArrayString = "";
            Map<String, String> keyTransformMap = new HashMap<>();
            String bcJsonArraySting = "";
            JSONArray bcNewJsonArray = new JSONArray();
            JSONArray bzJsonArray = dingUtil.getInnerTables(id, "FORM-3A8D681A77094B6DAF95EBB52ABF301DGFLW", "tableField_lxvknj7i");//计划单内包材子表
            if (!bzJsonArray.isEmpty()) {
                bcJsonArraySting = bzJsonArray.toString();
                keyTransformMap.put("textField_lxvknj78", "textField_ltzkj7lh");
                keyTransformMap.put("textField_lxvknj79", "textField_ltzkj7li");
                keyTransformMap.put("textField_lxvknj7a", "textField_lup11dxw");
                keyTransformMap.put("numberField_lxwv7czm", "numberField_lye43pr1"); // 采购数量
//                keyTransformMap.put("numberField_m4hx46fr", "numberField_lye43pr1"); // 采购数量
                keyTransformMap.put("imageField_lxvknj7e", "imageField_ltzkj7lj");
                bzArrayString = extracted(bcJsonArraySting, keyTransformMap, "包材", "件", "未采购");
                bcNewJsonArray = processJsonArray(bzArrayString);//去重

            }
            List<Object> oldJsonArrayList = new JSONArray().toList();
            List<Object> newJsonArrayList = new JSONArray().toList();
            String instanceId = "";
            if (!bcNewJsonArray.isEmpty()) {
                if (!searchJsonArray.isEmpty()) {
                    searchJsonReturnObject = searchJsonArray.getJSONObject(0);
                    instanceId = searchJsonReturnObject.getString("formInstanceId");
                    log.info("请购单id" + instanceId);
                    JSONArray oldBCJsonArray = dingUtil.getInnerTables(instanceId, "FORM-A79E0E23CFFD49F5B5A802BEDA6B6AF6CCYW", "tableField_ltzkj7lg");//请购单内子表
                    //获取旧数据
//                    JSONArray oldDJsonArray = new JSONArray();
                    if (!oldBCJsonArray.isEmpty()) {
                        //循环旧请购单，只拿棉纱和配件的物料
                        for (int i = 0; i < oldBCJsonArray.length(); i++) {
                            JSONObject jsonObject1 = oldBCJsonArray.getJSONObject(i);
                            String wlType = jsonObject1.has("textField_lx2wri52")?jsonObject1.getString("textField_lx2wri52"):"";
                            if (!wlType.equals("包材")){
                                oldJsonArrayList.add(jsonObject1);
                            }
                        }
//                        oldJsonArrayList = oldBCJsonArray.toList();
                    }
                }
                newJsonArrayList = new JSONArray(bcNewJsonArray).toList();
                JSONArray mergedArray = new JSONArray(
                        Stream.concat(oldJsonArrayList.stream(), newJsonArrayList.stream())
                                .collect(Collectors.toList())
                );
                JSONObject ownJson = new JSONObject();
                ownJson.put("tableField_ltzkj7lg", mergedArray);
                log.info("更新请购单");
                //新增并修改请购单
                //查询有没有当前请购单
                JSONObject searchFieldJson = new JSONObject();
                searchFieldJson.put("textField_lv5b06nc", jsonObject.getString("textField_lwt4u8ls"));//SO号
                searchFieldJson.put("textField_ltzkj7ld", jsonObject.getString("textField_lujgt578"));//请购单
                log.info("查询销售订单数据开始:{}", jsonObject.getString("textField_lwt4u8ls"));
                String yiDaSearchReturnData_XSDD = dingUtil.yiDaSearchReturnData("FORM-A79E0E23CFFD49F5B5A802BEDA6B6AF6CCYW", searchFieldJson);//获取销售订单数据
                String resString = null;
                if (yiDaSearchReturnData_XSDD.equals("[]") || yiDaSearchReturnData_XSDD.equals("") || yiDaSearchReturnData_XSDD.equals("null")){
                    log.info("新增");
                    JSONObject instanceJson = getInstanceJson(jsonObject, id, mergedArray);
                    resString = dingUtil.startInstance(instanceJson, userId, "FORM-A79E0E23CFFD49F5B5A802BEDA6B6AF6CCYW");
                }else{
                    log.info("更新");
                    if (Objects.equals(instanceId, "")){
                        JSONArray yiDaSearchReturnData_XSDDJsonArray = new JSONArray(yiDaSearchReturnData_XSDD);
                        instanceId = yiDaSearchReturnData_XSDDJsonArray.getJSONObject(0).getString("formInstanceId");
                    }
                    resString = dingUtil.UpdateYiDa(instanceId, ownJson);
                }
                log.info("请购单更新完成" + resString);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }



    private static JSONArray mergeJsonArrays(List<JSONArray>... jsonArrayLists) {
        return new JSONArray(Stream.of(jsonArrayLists)
                .filter(list -> list != null)
                .flatMap(List::stream)
                .collect(Collectors.toList()));
    }

    private String filterAndProcessJsonArray(String jsonString, String fieldName) throws JsonProcessingException, JsonMappingException {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(jsonString);
        ArrayNode arrayNode = (ArrayNode) rootNode;
        ArrayNode filteredArray = mapper.createArrayNode();

        arrayNode.forEach(node -> {
            if (node.has(fieldName) && "采购".equals(node.get(fieldName).asText())) {
                filteredArray.add(node);
            }
        });

        return filteredArray.toString();
    }

    private static String extracted(String jsonString, Map<String, String> keyTransformMap, String type, String unit, String status) throws JsonProcessingException, JsonMappingException {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(jsonString);
        ArrayNode arrayNode = (ArrayNode) rootNode;
        ArrayNode filteredArray = mapper.createArrayNode();
        arrayNode.forEach(node -> {
            ObjectNode filteredObject = mapper.createObjectNode();
            node.fields().forEachRemaining(field -> {
                if (keyTransformMap.containsKey(field.getKey())) {
                    filteredObject.set(keyTransformMap.get(field.getKey()), field.getValue());
                    filteredObject.put("textField_lx2wri52", type);
                    if (!unit.equals("无")) {
                        filteredObject.put("textField_lw4ngcq1", unit);
                    }
                    filteredObject.put("textField_lye3u67v", status);
                }
            });
            filteredArray.add(filteredObject);
        });
        return filteredArray.toString();
    }

    public static JSONArray processJsonArray(String jsonString) {
        JSONArray jsonArray = new JSONArray(jsonString);
        List<JSONObject> list = new ArrayList<>();
        for (int i = 0; i < jsonArray.length(); i++) {
            list.add(jsonArray.getJSONObject(i));
        }
        Map<String, List<JSONObject>> aggregatedMap = list.stream()
                .collect(Collectors.groupingBy(
                        jsonObject -> jsonObject.getString("textField_ltzkj7li"),
                        Collectors.mapping(json -> json, Collectors.toList())
                ));
        JSONArray resultArray = new JSONArray();
        aggregatedMap.forEach((key, values) -> {
            JSONObject resultObject = new JSONObject();
            // 设置 key1 的值
            resultObject.put("textField_ltzkj7li", key);
            // 累加 key2 的值
            Double sumOfKey2 = values.stream()
                    .mapToDouble(jsonObject -> jsonObject.has("numberField_lye43pr1") ? jsonObject.getDouble("numberField_lye43pr1") : 0)
                    .sum();
            resultObject.put("numberField_lye43pr1", sumOfKey2);
            // 保留第一个对象的 key3, key4, key5 的值
            JSONObject firstObject = values.get(0);
            resultObject.put("textField_ltzkj7lh", firstObject.has("textField_ltzkj7lh") ? firstObject.get("textField_ltzkj7lh") : "");
            resultObject.put("textField_lup11dxw", firstObject.has("textField_lup11dxw") ? firstObject.get("textField_lup11dxw") : "");
            resultObject.put("imageField_ltzkj7lj", firstObject.has("imageField_ltzkj7lj") ? firstObject.get("imageField_ltzkj7lj") : "");
            resultObject.put("textField_lx2wri52", firstObject.has("textField_lx2wri52") ? firstObject.get("textField_lx2wri52") : "");
            resultObject.put("textField_lw4ngcq1", firstObject.has("textField_lw4ngcq1") ? firstObject.get("textField_lw4ngcq1") : "");
            resultObject.put("textField_lye3u67v", firstObject.has("textField_lye3u67v") ? firstObject.get("textField_lye3u67v") : "");
            // 将结果对象添加到结果数组中
             resultArray.put(resultObject);
        });
        return resultArray;
    }

    private static JSONObject getInstanceJson(JSONObject jsonObject, String id, JSONArray mergedArray) {
        JSONObject ownJson = new JSONObject();
//        ownJson.put("associationFormField_lw4nquy4", jsonArrayOne);//关联bom
        if (jsonObject.has("tableField_m0gbvy0a")) {
            JSONArray jsonArrayOne = jsonObject.getJSONArray("tableField_m0gbvy0a");
            List<JSONObject> listJOSNObject = new ArrayList<>();
            for (int i = 0; i < jsonArrayOne.length(); i++) {
                JSONObject jsonArrayTow = new JSONObject();
                JSONObject jsonArrayThree = jsonArrayOne.getJSONObject(i);
                String substring = jsonArrayThree.getString("associationFormField_m0wbjlek_id").replaceAll("\\\\", "").substring(1);
                String instanceId = new JSONArray(substring.substring(0, substring.length() - 1)).getJSONObject(0).getString("instanceId");
                JSONArray jsonArray = FormUtils.getAssociationFormField("FORM-1302BBEC3D914EBAAF95451A6DCE345ARF8K", jsonArrayThree.get("textField_m0xlus2q").toString(), instanceId);
                jsonArrayTow.put("associationFormField_m0wbjlek", jsonArray);
                jsonArrayTow.put("numberField_m35oagj0", jsonArrayThree.get("numberField_m1hv1yu8"));
                jsonArrayTow.put("numberField_m4l3ucjc", jsonArrayThree.get("numberField_m2aidy02"));
                listJOSNObject.add(jsonArrayTow);
            }
            ownJson.put("tableField_m0gbvy0a", listJOSNObject);
        }
        ownJson.put("tableField_ltzkj7lg", mergedArray);
        ownJson.put("textField_ltzkj7ld", jsonObject.get("textField_lujgt578"));//客户名称
//        ownJson.put("textField_ly89l9at", jsonObject.get("textField_lujgt576"));//成品AC号
        ownJson.put("textField_lv5b06nc", jsonObject.get("textField_lwt4u8ls"));//SO号
//        ------------------------关联表单生产计划-----------------------------
        String title = jsonObject.getString("textField_lwt4u8ls");
        String fromUuid = "FORM-3A8D681A77094B6DAF95EBB52ABF301DGFLW";
        // 通过调用FormUtils的getAssociationFormField方法，根据fromUuid、title和id获取关联表单字段的JSON数组
        JSONArray jsonArrayOne = FormUtils.getAssociationFormField(fromUuid, title, id);
        ownJson.put("associationFormField_m4gsfpy0", jsonArrayOne);
        return ownJson;
    }

    /**
     * 刷新请购单的
     * @param id
     */
    @Override
    @Async
    public void refreshPurchaseOrder(String id,String poId) throws Exception {
        //查询当前派工单的入库数据
        JSONObject json = new JSONObject();
        json.put("textField_lv5fbxkd", poId);//SO号
        String ss = dingUtil.yiDaSearchReturnData("FORM-434F54618CD44D8C9A220DA804F86FEEANNV", json);//获取销售订单数据
        JSONArray JsonArray = new JSONArray(ss);
        double total = 0; //总数
        double sumAmount = 0; //总价
        for (int i = 0; i < JsonArray.length(); i++) {
//            JSONObject bomOneJson = JsonArray.getJSONObject(i);
            JSONObject bomOneJson = JsonArray.getJSONObject(i).getJSONObject("formData");
            total = total + (bomOneJson.has("numberField_m3wmz69o")?bomOneJson.getDouble("numberField_m3wmz69o"):0);
            sumAmount = sumAmount + (bomOneJson.has("numberField_lv6cq6hx")?bomOneJson.getDouble("numberField_lv6cq6hx"):0);
        }
        String yidaById = dingUtil.getYidaById(id);
        JSONObject jsonObject = new JSONObject(yidaById);
        double CG_Amount = 0 ;
        double JK_total = 0 ;
        JSONObject object = new JSONObject();
        if (jsonObject.has("numberField_luozyti2")){
            CG_Amount = jsonObject.getDouble("numberField_luozyti2");//采购总金额
        }
        if (jsonObject.has("numberField_mg07yjr0")){
            JK_total = jsonObject.getDouble("numberField_luozyti2");//入库总数
            object.put("numberField_m3wmr7a6",JK_total-total);//待入库数量
        }else{
            object.put("numberField_m3wmr7a6","0");//待入库数量
        }
        double fukuanJE = 0; //付款金额
        if (jsonObject.has("numberField_luozyti8")){
            fukuanJE = jsonObject.getDouble("numberField_luozyti8");
        }
        object.put("numberField_m3wmr7a8",total);//已入库数量
        object.put("numberField_m5c1lqd2",sumAmount);//到货金额
        object.put("numberField_m5ouvwv1",fukuanJE - sumAmount);//订单内待付金额
        object.put("numberField_m5ouvwv2",sumAmount);//订单内待开票金额
        object.put("textField_m3wmr7aa",CG_Amount<=sumAmount?"已入库":"未入库");//入库状态
        dingUtil.UpdateYiDa(id, object);
    }
}
